package global

import (
	"encoding/json"
	"flag"
	"io/ioutil"
	"log"
	"os"
	"path/filepath"
	"strings"

	"away.wei/minidevpos/db"
	"away.wei/minidevpos/model"
	"gopkg.in/yaml.v2"
	"gorm.io/gorm"
)

var (
	args             string
	Settings         Appsettings
	DB               *gorm.DB
	Abpath           = getAbPath()
	DevOpsCancelChan = make(chan int)                 // 构建任务取消管道
	BroadcastChan    = make(chan model.SocketMessage) // websocket事件管道
	DevOpsEventAPP   = new(DevOpsEvent)
)

func New() {
	flag.StringVar(&args, "c", "", "选择appsettings.yaml文件路径,默认 ./appsettings.yaml")
	flag.Parse()
	if args == "" {
		args = "./appsettings.yaml"
		log.Printf("您正在使用默认配置文件路径为./appsettings.yaml")
	} else {
		log.Printf("您正在使用命令行的-c参数传递的值,配置文件路径为%v\n", args)
	}
	getYaml(args, &Settings)

	var err error
	DB, err = db.New(Settings.DB)
	if err != nil {
		log.Println("数据库初始化失败：", err.Error())
	}
}

func getAbPath() string {
	exePath, _ := os.Executable()
	abpath, _ := filepath.EvalSymlinks(filepath.Dir(exePath))
	return strings.ReplaceAll(abpath, "\\", "/")
}

func getYaml(appsettingPath string, appsettings *Appsettings) {

	b, err := ioutil.ReadFile(appsettingPath)
	if err != nil {
		log.Println("读取appsetting.yaml失败：", err.Error())
		os.Exit(0)
		return
	}
	if err := yaml.Unmarshal(b, &appsettings); err != nil {
		log.Println("读取appsetting.yaml失败：", err.Error())
	}
}

type DevOpsEvent struct{}

func (*DevOpsEvent) Emit(eventName string, args string) {
	BroadcastChan <- model.SocketMessage{
		EventName: eventName,
		Args:      args,
	}
}
func (s *DevOpsEvent) EmitJson(eventName string, args interface{}) {
	b, _ := json.Marshal(args)
	s.Emit(eventName, string(b))
}

func (*DevOpsEvent) CancelTask(projectId int) {
	DevOpsCancelChan <- projectId
}
